//
//  NSAttributedString+ZXCategory.m
//  YiShangbao
//
//  Created by simon on 2018/6/25.
//  Copyright © 2018年 com.Microants. All rights reserved.
//

#import "NSAttributedString+ZXCategory.h"
#import <UIKit/UIKit.h>
#import "UIColor+ZXHex.h"

@implementation StyleList



@end

@implementation NSAttributedString (ZXCategory)


+ (NSAttributedString *)zx_attributedStringWithStrikethroughStyleWithString:(NSString *)str
{
    if (!str) {
        return nil;
    }
    NSDictionary *attribtDic = @{NSStrikethroughStyleAttributeName: [NSNumber numberWithInteger:NSUnderlineStyleSingle]};
    NSAttributedString *attStr = [[NSAttributedString alloc]initWithString:str attributes:attribtDic];
    return attStr;
}

+ (NSAttributedString *)zx_attributedStringWithUnderlineStyleWithString:(NSString *)str
{
    if (!str) {
        return nil;
    }
    NSDictionary *attribtDic = @{NSUnderlineStyleAttributeName: [NSNumber numberWithInteger:NSUnderlineStyleSingle]};
    NSAttributedString *attStr = [[NSAttributedString alloc]initWithString:str attributes:attribtDic];
    return attStr;
}


- (NSAttributedString *)zx_addStrikethroughTypeSingleWithRange:(NSRange)range strikethroughColor:(UIColor *)color
{
    NSMutableAttributedString *attMString = [[NSMutableAttributedString alloc] initWithAttributedString:self];
    
    if(range.location > self.length || range.length > self.length - range.location)
    {
        [NSException raise:NSRangeException format:@"out of range"];
    }
    [attMString addAttribute:NSStrikethroughStyleAttributeName value:@(NSUnderlineStyleSingle) range:range];
    if (color)
    {
        [attMString addAttribute:NSStrikethroughColorAttributeName value:color range:range];
    }
    return attMString;
}



/*
 + (NSAttributedString *)zx_attributedStringWithModel:(CHSAttributedText *)attTextModel regularAttributes:(NSDictionary *)regularAttributes
 {
     if (!attTextModel) {
         return nil;
     }
     NSString *textStr = attTextModel.text;
     NSArray *prices = attTextModel.paramList;
     NSArray <StyleList *> *styles = attTextModel.styleList;

     if ([NSString zx_isBlankString:textStr]) {
         return nil;
     }
     if (!regularAttributes) {
         regularAttributes = @{NSFontAttributeName:[UIFont zx_systemFontOfSize:14],NSForegroundColorAttributeName:[UIColor zx_colorWithHexString:@"#333333"]};
     }
     NSMutableAttributedString *mAttributedStr = [[NSMutableAttributedString alloc] initWithString:textStr attributes:regularAttributes];
     return [NSAttributedString zx_attributedStringWithAttributedString:mAttributedStr replaceIdString:@"%s" targets:prices styles:styles];
 }
 */

+ (nullable NSMutableAttributedString *)zx_attributedStringWithAttributedString:(nullable NSAttributedString *)full
                                                       replaceIdString:(nullable NSString *)replaceIdString
                                                               targets:(NSArray *)targets
                                                                styles:(NSArray <StyleList *> *)styles
{
    NSMutableAttributedString *mAttributedString = [[NSMutableAttributedString alloc] init];
    if (!full || full.length == 0) {
        return nil;
    }
    //默认属性
    NSDictionary *regularAttributes = [full attributesAtIndex:0 effectiveRange:NULL];
    if (!regularAttributes) {
        regularAttributes = @{NSFontAttributeName:[UIFont systemFontOfSize:14],NSForegroundColorAttributeName:[UIColor zx_colorWithHexString:@"#333333"]};
    }
    NSString *fullString = full.string;
    //默认替换符
    if (!replaceIdString) {
        replaceIdString = @"%s";
    }
    //分隔符分割数组
    NSArray *seperateStrings = [fullString componentsSeparatedByString:replaceIdString];
    [seperateStrings enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
        NSAttributedString *attStr = [[NSAttributedString alloc] initWithString:obj attributes:regularAttributes];
        [mAttributedString appendAttributedString:attStr];
        if (idx >= seperateStrings.count-1) {
            return;
        }
        if (idx >= targets.count) {
            return;
        }
        NSString *price = [targets objectAtIndex:idx];
        NSMutableAttributedString *attPrice = [[NSMutableAttributedString alloc] initWithString:price];
        if (idx < styles.count) {
            NSMutableDictionary *attrs = [@{} mutableCopy];
            StyleList *styleModel = [styles objectAtIndex:idx];
            UIFontWeight weight;
            if ([styleModel.weight isEqualToString:@"normal"]) {
                weight = UIFontWeightRegular;
            }else if ([styleModel.weight isEqualToString:@"bold"])
            {
                weight = UIFontWeightBold;
            }else
            {
                weight = UIFontWeightLight;
            }
            UIFont *font = [UIFont systemFontOfSize:styleModel.size *([UIScreen mainScreen].bounds.size.width/375) weight:weight];
            [attrs setValue:font forKey:NSFontAttributeName];
            [attrs setValue:[UIColor zx_colorWithHexString:styleModel.color] forKey:NSForegroundColorAttributeName];
            if ([styleModel respondsToSelector:@selector(textDecoration)] && [styleModel.textDecoration isEqualToString:@"line_through"]) {
//                [attrs setValue:@(NSUnderlineStyleSingle) forKey:NSBaselineOffsetAttributeName];
                [attrs setValue:@(NSUnderlinePatternSolid|NSUnderlineStyleSingle) forKey:NSStrikethroughStyleAttributeName];
                [attrs setValue:[UIColor zx_colorWithHexString:styleModel.color] forKey:NSStrikethroughColorAttributeName];
            }
            
            [attPrice addAttributes:attrs range:NSMakeRange(0, attPrice.length)];
        }
        [mAttributedString appendAttributedString:attPrice];
    }];
    return mAttributedString;
}


@end



@implementation NSMutableAttributedString (ZXCategory)


- (NSMutableAttributedString *)zx_addLineSpace:(CGFloat)lineSpace
{
    NSMutableAttributedString *attributedString = [self zx_addLineSpace:lineSpace alignment:NSTextAlignmentLeft lineBreakMode:NSLineBreakByTruncatingTail];
    return attributedString;
}

- (NSMutableAttributedString *)zx_addLineSpace:(CGFloat)lineSpace alignment:(NSTextAlignment)alignment{
    NSMutableAttributedString *attributedString = [self zx_addLineSpace:lineSpace alignment:alignment lineBreakMode:NSLineBreakByTruncatingTail];
    return attributedString;
}


- (NSMutableAttributedString *)zx_addLineSpace:(CGFloat)lineSpace
                                     alignment:(NSTextAlignment)alignment
                                 lineBreakMode:(NSLineBreakMode) lineBreakMode
{
    NSMutableParagraphStyle * style = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
    style.lineSpacing = lineSpace;//行距
    style.alignment = alignment;
    style.lineBreakMode = lineBreakMode;
    [self addAttribute:NSParagraphStyleAttributeName value:style range:NSMakeRange(0, self.length)];
    return self;
}

- (void)zx_enumerateRangeOfString:(NSString *)searchString usingBlock:(void(^)(NSRange searchStringRange,NSUInteger idx, BOOL *stop))block
{
    if (self.length && searchString.length) {
        
        NSArray <NSString *>*separatedArray = [self.string componentsSeparatedByString:searchString];
        if (separatedArray.count <2) {
            return;
        }
        NSUInteger count = separatedArray.count -1;
        NSUInteger length = searchString.length;
        __block NSUInteger location = 0;
        [separatedArray enumerateObjectsUsingBlock:^(NSString * _Nonnull componentString, NSUInteger idx, BOOL * _Nonnull stop) {
            if (idx == count) {
                *stop = YES;
            }else{
                location += componentString.length;//跳过待筛选串前面的串长度
                if (block) {
                    block(NSMakeRange(location, length),idx,stop);
                }
                location += length;//跳过待筛选串的长度
            }
        }];
    }
}

- (void)zx_enumerateDecimalNumberWithDotSeperateUsingDotPrefixBlock:(void(^)(NSRange dotPrefixRange))prefixBlock dotSuffixBlock:(void(^)(NSRange dotSuffixRange))suffixBlock
{
    if (self.length == 0) {
        return;
    }
    NSString *dotPrefixString = nil;
    NSString *dotSuffixString = nil;
    if ([self.string containsString:@"."]) {
       
        NSArray <NSString *>*separatedArray = [self.string componentsSeparatedByString:@"."];
        dotPrefixString = [separatedArray firstObject];
        dotSuffixString = [separatedArray lastObject];
        if (suffixBlock) {
            //当999.99，dotSuffixString也能在小数点前面找到的时候,会返回前面的range[0,2]
//                [self.string rangeOfString:dotSuffixString],会造成错误；
           suffixBlock(NSMakeRange(dotPrefixString.length+1, dotSuffixString.length));
        }
    }
    //没有小数点后面的数字时候，后缀block不回调；
    else
    {
        dotPrefixString = self.string;
    }
    if (prefixBlock) {
        prefixBlock([self.string rangeOfString:dotPrefixString]);
    }
}


- (void)zx_insetPrefixAttachmentLabelWithLabelTitle:(NSString *)title
                                          textColor:(nullable UIColor *)textColor
                                          titleFont:(nullable UIFont *)titleFont
                                       contentInset:(UIEdgeInsets)contentInset
                                  labelCornerRadius:(CGFloat)radius
                                        borderWidth:(CGFloat)borderWidth
                                        borderColor:(nullable UIColor *)borderColor
                                    backgroundColor:(nullable UIColor *)backgroundColor
{
    if (!title || title == NULL
        ||[title isKindOfClass:[NSNull class]]
        || title.length == 0) {
        return;
    }
    UIEdgeInsets inset = UIEdgeInsetsEqualToEdgeInsets(contentInset, UIEdgeInsetsZero) ? UIEdgeInsetsMake(1, 2, 1, 2) :contentInset;
    if (!titleFont) {
        titleFont = [UIFont systemFontOfSize:11];
    }
    CGFloat scale = [UIScreen mainScreen].scale;
    UILabel *lab = [UILabel new];
    lab.text = title;
    UIFont *cFont = [titleFont fontWithSize:titleFont.pointSize*scale];
    lab.font = cFont;
    lab.textColor = textColor ? textColor : [UIColor blackColor];
    lab.backgroundColor = backgroundColor ? backgroundColor: [UIColor whiteColor];
    lab.textAlignment = NSTextAlignmentCenter;
 
    NSMutableDictionary *attrMDic = [NSMutableDictionary new];
    [attrMDic setObject:lab.font forKey:NSFontAttributeName];
    NSMutableParagraphStyle *style = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
     style.lineBreakMode = NSLineBreakByWordWrapping;
    [attrMDic setObject:style forKey:NSParagraphStyleAttributeName];
    CGSize textSize = [lab.text boundingRectWithSize:CGSizeMake(CGRectGetWidth(UIScreen.mainScreen.bounds), CGFLOAT_MAX)
                              options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
                           attributes:attrMDic
                              context:nil].size;
    CGFloat labW = textSize.width +(inset.left+inset.right) *scale;
    CGFloat labH = textSize.height +(inset.top+inset.bottom) *scale;
    lab.frame = CGRectMake(0, 0, labW, labH);

    lab.layer.masksToBounds = YES;
    lab.layer.cornerRadius = radius *scale;
    lab.layer.borderWidth = borderWidth *scale;
    lab.layer.borderColor = borderColor?[borderColor CGColor]:lab.textColor.CGColor;
    //scale比例的图片,不然会虚
    UIImage *image = [self imageWithUIView:lab];
    
    NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
    //这个-3是为了调整下标签跟文字的位置
    attachment.bounds = CGRectMake(0, -2.5-(inset.bottom+inset.top)/2, CGRectGetWidth(lab.bounds)/scale, CGRectGetHeight(lab.bounds)/scale);
    attachment.image = image;
    //添加到富文本对象里
    NSAttributedString *imageAttributedString = [NSAttributedString attributedStringWithAttachment:attachment];
    [self insertAttributedString:imageAttributedString atIndex:0];
    [self insertAttributedString:[[NSAttributedString alloc]initWithString:@" "] atIndex:1];

}


- (void)zx_insetPrefixAttachmentButtonWithIconImage:(UIImage *)iconImage
                                         labelTitle:(NSString *)title
                                          textColor:(nullable UIColor *)textColor
                                          titleFont:(nullable UIFont *)titleFont
                                       contentInset:(UIEdgeInsets)contentInset
                                  labelCornerRadius:(CGFloat)radius
                                        borderWidth:(CGFloat)borderWidth
                                        borderColor:(nullable UIColor *)borderColor
                                    backgroundColor:(nullable UIColor *)backgroundColor
{
    if (!title || title == NULL
        ||[title isKindOfClass:[NSNull class]]
        || title.length == 0) {
        return;
    }
    UIEdgeInsets inset = UIEdgeInsetsEqualToEdgeInsets(contentInset, UIEdgeInsetsZero) ? UIEdgeInsetsMake(1, 2, 1, 2) :contentInset;
    if (!titleFont) {
        titleFont = [UIFont systemFontOfSize:11];
    }
    CGFloat scale = [UIScreen mainScreen].scale;
    UIButton *view = [UIButton new];
    [view setTitle:title forState:UIControlStateNormal];
    UIFont *cFont = [titleFont fontWithSize:titleFont.pointSize*scale];
    view.titleLabel.font =cFont;
    UIColor *cColor = textColor ? textColor : [UIColor blackColor];
    [view setTitleColor:cColor forState:UIControlStateNormal];
    
    UIColor *cBgColor = backgroundColor ? backgroundColor: [UIColor whiteColor];
    view.backgroundColor = cBgColor;
    
    NSData *data = UIImagePNGRepresentation(iconImage);
    UIImage *cImage = [UIImage imageWithData:data];
    [view setImage:cImage forState:UIControlStateNormal];
 
    NSMutableDictionary *attrMDic = [NSMutableDictionary new];
    [attrMDic setObject:cFont forKey:NSFontAttributeName];
    NSMutableParagraphStyle *style = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
     style.lineBreakMode = NSLineBreakByWordWrapping;
    [attrMDic setObject:style forKey:NSParagraphStyleAttributeName];
    CGSize textSize = [title boundingRectWithSize:CGSizeMake(CGRectGetWidth(UIScreen.mainScreen.bounds), CGFLOAT_MAX)
                              options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
                           attributes:attrMDic
                              context:nil].size;
    CGFloat labW = textSize.width +(inset.left+inset.right) *scale + cImage.size.width;
    CGFloat maxH = MAX(textSize.height, cImage.size.height);
    CGFloat labH =  maxH +(inset.top+inset.bottom) *scale;
    view.frame = CGRectMake(0, 0, labW, labH);

    view.layer.masksToBounds = YES;
    view.layer.cornerRadius = radius *scale;
    view.layer.borderWidth = borderWidth * scale;
    view.layer.borderColor = borderColor?[borderColor CGColor]:view.currentTitleColor.CGColor;

    UIImage *image = [self imageWithUIView:view];
    
    NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
    //这个-3是为了调整下标签跟文字的位置
    attachment.bounds = CGRectMake(0, -2.5-(inset.bottom+inset.top)/2, CGRectGetWidth(view.bounds)/scale, CGRectGetHeight(view.bounds)/scale);
    attachment.image = image;
    //添加到富文本对象里
    NSAttributedString *imageAttributedString = [NSAttributedString attributedStringWithAttachment:attachment];
    [self insertAttributedString:imageAttributedString atIndex:0];
    [self insertAttributedString:[[NSAttributedString alloc]initWithString:@" "] atIndex:1];

}


//view转成image
- (UIImage *)imageWithUIView:(UIView *)view{
    UIGraphicsBeginImageContext(CGSizeMake(view.bounds.size.width, view.bounds.size.height));
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    [view.layer renderInContext:ctx];
    UIImage* tImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return tImage;
}



+ (NSMutableAttributedString *)zx_attributedStringWithPrefixCNYString:(NSString *)amountString symbolAttributes:(NSDictionary<NSAttributedStringKey, id> *)symbolAttrs priceAttributes:(NSDictionary<NSAttributedStringKey, id> *)priceAttrs
{
    if (!amountString) {
        return nil;
    }
    //如果为nil，则[amountString floatValue]=0;
    NSDecimalNumber *priceNumber = [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%.2f",[amountString floatValue]] locale:[NSLocale currentLocale]];
    NSMutableString *priceString = [NSMutableString stringWithFormat:@"%@",[priceNumber description]];
    if (![amountString containsString:@"¥"]) {
        [priceString insertString:@"¥" atIndex:0];
    }
    NSMutableAttributedString *attri = [[NSMutableAttributedString alloc] initWithString:priceString];
    if (!symbolAttrs) {
        symbolAttrs = @{NSFontAttributeName:[UIFont systemFontOfSize:17 weight:UIFontWeightMedium],};
    }
    [attri addAttributes:symbolAttrs range:NSMakeRange(0, 1)];
    if (!priceAttrs) {
        priceAttrs = @{NSFontAttributeName:[UIFont systemFontOfSize:33 weight:UIFontWeightMedium],};
    }
    [attri addAttributes:priceAttrs range:NSMakeRange(1, attri.length-1)];
    return attri;
}



@end
